from django.shortcuts import render
from django.views import View
from .models import Area,House
from django.http import JsonResponse
import json
from ihome.utils.views import LoginRequiredJsonMixin
# Create your views here.


# 获取城区数据
class CitylistView(View):

    def get(self,request):

        citys = Area.objects.filter()

        city_list = []
        for city in citys:
            city_list.append({
                'aid':city.id,
                'aname':city.name
            })

        return JsonResponse({
            'errmsg':'获取成功',
            'errno':0,
            'data':city_list
        })

# 发布房源
class RentalView(LoginRequiredJsonMixin,View):

    def post(self,request):

        # 提取参数
        data = json.loads(request.body.decode())

        title = data.get('title')
        price = data.get('price')
        area_id = data.get('area_id')
        address = data.get('address')
        room_count = data.get('room_count')
        acreage = data.get('acreage')
        unit = data.get('unit')
        capacity = data.get('capacity')
        beds = data.get('beds')
        deposit = data.get('deposit')
        min_days = data.get('min_days')
        max_days = data.get('max_days')
        facility = data.get('facility')


        # 校验参数
        if not all([title,price,area_id,address,room_count,acreage,unit,capacity,beds,deposit,min_days,max_days,facility]):
            return JsonResponse({
                'errno':4101,
                'errmsg':'缺少必要性参数'
            })

        try:
            city = Area.objects.get(pk=area_id)
        except Area.DoesNotExist as e:
            return JsonResponse({
                'errno':4101,
                'errmsg':'地址不存在'
            })

        # 构建响应参数
        new_house = House.objects.create(
            facility=facility,
            deposit=deposit,
            title=title,
            price=price,
            area_id=area_id,
            address=address,
            room_count=room_count,
            acreage=acreage,
            unit=unit,
            capacity=capacity,
            beds=beds,
            min_days=min_days,
            max_days=max_days,
        )

        # 返回响应
        return JsonResponse({
            'errno':0,
            'errmsg':'发布成功',
            'data': {
                new_house.id
            }

        })
